
#include <stdint.h>
#include <arm_compat.h>
#include "LedId.h"
#include "Bsp_Led.h"
#include "Led.h"
#include "Timer.h"

static Timer_T ledTimer;

static uint8_t ledLockMask;
static uint8_t ledFlashMap;

static uint8_t ledCount;

static void LedFlashCallback(void){
	++ledCount;
	if(ledFlashMap & Led_Mask(LedId_White)){
		BSP_Led_SetState(LedId_White, ledCount & 0x01);
	}
	if(ledFlashMap & Led_Mask(LedId_Greent)){
		BSP_Led_SetState(LedId_Greent, ledCount & 0x01);
	}
}

void Led_Init(void){
	ledLockMask = 0;
	ledFlashMap = 0;
	Timer_Setup(&ledTimer, 100, 1, 0, LedFlashCallback);
//		Timer_Restart(&ledTimer);
}

void Led_On(LedId_T id){
	if(ledLockMask & Led_Mask(id)){
		return ;
	}
	ledFlashMap &= ~ Led_Mask(id);
	if(ledFlashMap == 0){
		Timer_Stop(&ledTimer);
	}
	BSP_Led_On(id);
}

void Led_Off(LedId_T id){
	if(ledLockMask & Led_Mask(id)){
		return ;
	}
	ledFlashMap &= ~ Led_Mask(id);
	if(ledFlashMap == 0){
		Timer_Stop(&ledTimer);
	}
	BSP_Led_Off(id);
}

void Led_Set(LedId_T Id, uint8_t state){
	if(state){
		Led_On(Id);
	}
	else{
		Led_Off(Id);
	}
}

void Led_Toggle(LedId_T Id){
	if(ledLockMask & Led_Mask(Id)){
		return ;
	}
	Led_Set(Id, !BSP_Led_GetState(Id));
}

void Led_Flash(LedId_T id){
	if(ledLockMask & Led_Mask(id)){
		return ;
	}
	ledFlashMap |= Led_Mask(id);
	if(!Timer_IsActive(&ledTimer) || ledTimer.period != 100){
		Timer_Reset(&ledTimer, 100);
	}
	BSP_Led_Off(id);
}

static void Led_DoMultSet(uint8_t ledMap, uint8_t stateMap){
	uint8_t i;
	for(i = 0; i < sizeof(ledMap) * 8; ++i){
		if(ledMap & Led_Mask(i)){
			BSP_Led_SetState(i, stateMap & Led_Mask(i));
		}
	}
}


//同步设置
void Led_MultSet(uint8_t ledMap, uint8_t stateMap){
	if(ledLockMask & ledMap){
		return ;
	}
	__disable_irq();
	ledFlashMap &= ~ ledMap;
	if(ledFlashMap == 0){
		Timer_Stop(&ledTimer);
	}
	Led_DoMultSet(ledMap, stateMap);
	__enable_irq();
}

//以某个间隔同步闪烁
void Led_MultFlashFreq(uint8_t ledMap, uint16_t period){
	if(ledLockMask & ledMap){
		return ;
	}
	Timer_Stop(&ledTimer);
	Led_DoMultSet(Led_MaskAll, 0);
	ledFlashMap = ledMap;
	Timer_Reset(&ledTimer, period / 10);
}

//同步闪烁
void Led_MultFlashSync(uint8_t ledMap){
	Led_MultFlashFreq(ledMap, 1000);
}

void Led_MultLock(uint8_t ledMap){
	ledLockMask |= ledMap;
}

void Led_MultUnLock(uint8_t ledMap){
	ledLockMask &= ~ ledMap;
}


void Led_Lock(LedId_T Id){
	ledLockMask |= 1 << Id;
}

void Led_Unlock(LedId_T Id){
	ledLockMask &= ~(1 << Id);
}

int Led_State(LedId_T Id){
	return BSP_Led_GetState(Id);
}

int Led_Check(LedId_T id){
	if(ledFlashMap & Led_Mask(id)){
		return 2;
	}
	return Led_State(id);
}


